//
//  SignViewController.swift
//  Ruisi
//
//  Created by yang on 2017/6/24.
//  Copyright © 2017年 yang. All rights reserved.
//

import UIKit
import Kanna
import IntentsUI

// 签到页面
// 支持siri捷径 https://www.appcoda.com/siri-shortcuts/
// https://www.jianshu.com/p/19b248333b18
class SignViewController: UIViewController {

    // 是否从捷径打开
    var openFromSiri = false

    let items = ["开心", "难过", "郁闷", "无聊", "怒", "擦汗", "奋斗", "慵懒", "衰"]
    let itemsValue = ["kx", "ng", "ym", "wl", "nu", "ch", "fd", "yl", "shuai"]
    @IBOutlet weak var loadingView: UIActivityIndicatorView!
    @IBOutlet weak var signingView: UIActivityIndicatorView!
    
    @IBOutlet weak var labelSmiley: UILabel!
    @IBOutlet weak var btnSmiley: UIButton!
    @IBOutlet weak var inputText: UITextField!
    @IBOutlet weak var btnSign: UIButton!
    @IBOutlet weak var haveSignImg: UIImageView!
    @IBOutlet weak var labelStatus: UILabel!
    @IBOutlet weak var labelTotal: UILabel!
    @IBOutlet weak var labelTotal2: UILabel!
    @IBOutlet weak var addToSiriBtn: UIButton!
    
    var isSigned: Bool = false {
        didSet {
            haveSignImg.isHidden = !isSigned
            labelStatus.isHidden = !isSigned
            labelTotal.isHidden = !isSigned
            labelTotal2.isHidden = !isSigned

            labelSmiley.isHidden = isSigned
            btnSmiley.isHidden = isSigned
            inputText.isHidden = isSigned
            btnSign.isHidden = isSigned
            
            signingView.stopAnimating()
        }
    }
    var chooseAlert: UIAlertController!
    var currentSelect = 0

    @IBAction func confirmClick(_ sender: UITextField) {
        inputText.resignFirstResponder()
    }

    func setLoadingState(isLoading: Bool) {
        loadingView.isHidden = !isLoading
        if isLoading {
            haveSignImg.isHidden = true
            labelStatus.isHidden = true
            labelTotal.isHidden = true
            labelTotal2.isHidden = true

            labelSmiley.isHidden = true
            btnSmiley.isHidden = true
            inputText.isHidden = true
            btnSign.isHidden = true
        }
    }


    @IBAction func chooseClick(_ sender: UIButton) {
        self.inputText.resignFirstResponder()
        present(chooseAlert, animated: true, completion: nil)
    }

    @IBAction func signBtnClick(_ sender: UIButton? = nil) {
        self.inputText.resignFirstResponder()
        setSigningState(signing: true)
        let xinqin = itemsValue[currentSelect]
        let say = inputText.text

        let qmode: String
        if say == nil {
            qmode = "1"
        } else {
            qmode = "3"
        }

        HttpUtil.POST(url: Urls.signPostUrl, params: ["qdxq": xinqin, "qdmode": qmode, "todaysay": say ?? "来自手机睿思IOS", "fastreplay": 0]) { ok, res in
            let message: String
            let success: Bool
            
            if ok, let s = res.range(of: "恭喜你签到成功") {
                success = true
                let end = res.range(of: "</div>", options: .literal, range: s.upperBound..<res.endIndex)
                message = String(res[s.lowerBound..<end!.lowerBound])
            } else if let eStart = res.range(of: "class=\"c\">")?.upperBound {
                //<div class="c">对不起，您所在的用户组未被加入允许签到的行列. </div>
                success = false
                let eEnd = res.range(of: "</div>", range: eStart..<res.endIndex)!.lowerBound
                message = String(res[eStart..<eEnd])
            } else {
                message = Utils.getRuisiReqError(res: res) ?? res
                success = false
            }

            DispatchQueue.main.async { [weak self] in
                self?.setSigningState(signing: false)
                let vc = UIAlertController(title: success ? "签到成功" : "签到失败", message: message, preferredStyle: .alert)
                vc.addAction(UIAlertAction(title: "好", style: .cancel))
                self?.present(vc, animated: true)
                self?.openFromSiri = false
                self?.checkSignStatus()
            }
        }
    }

    // 处理选择心情
    func handlePick(action: UIAlertAction) {
        let title = action.title
        for (i, v) in items.enumerated() {
            if v == title {
                currentSelect = i
                btnSmiley.setTitle(title, for: .normal)
                btnSmiley.setTitle(title, for: .focused)
                break
            }
        }
    }

    // 检查是否签到
    func checkSignStatus() {
        setLoadingState(isLoading: true)
        HttpUtil.GET(url: Urls.signUrl, params: nil) { ok, res in
            DispatchQueue.main.async { [weak self] in
                self?.setLoadingState(isLoading: false)
                if ok, let doc = try? HTML(html: res, encoding: .utf8) {
                    if res.contains("您今天已经签到过了或者签到时间还未开始") {
                        var daytxt = "0"
                        var monthtxt = "0"
                        for ele in doc.css(".mn p") {
                            if ele.text!.contains("您累计已签到") {
                                let r = ele.text!.range(of: "您累计已签到")
                                daytxt = String(ele.text![r!.lowerBound...])
                            } else if ele.text!.contains("您本月已累计签到") {
                                monthtxt = ele.text!
                            }
                        }
                        self?.labelStatus.text = "今日已签到"
                        self?.labelTotal.text = daytxt
                        self?.labelTotal2.text = monthtxt
                        self?.isSigned = true
                    } else {
                        self?.isSigned = false
                        if self?.openFromSiri ?? false {
                            self?.signBtnClick()
                        }
                    }
                } else {
                    self?.labelStatus.isHidden = false
                    self?.labelStatus.text = "非校园网无法签到"
                }
            }
        }
    }

    func setSigningState(signing: Bool) {
        if signing {
            signingView.startAnimating()
            btnSign.setTitle("签到中...", for: .normal)
            inputText.isEnabled = false
        } else {
            signingView.stopAnimating()
            btnSign.setTitle("开始签到", for: .normal)
            inputText.isEnabled = true
        }
    }
    
    
    //com.xdluoyang.Ruisi.sign
    func setupIntents() -> NSUserActivity {
        let activity = NSUserActivity(activityType: "com.xdluoyang.Ruisi.sign") // 1
        activity.title = "睿思签到" // 2
        activity.userInfo = ["data1" : "value1"] // 3
        activity.isEligibleForSearch = true // 4
        if #available(iOS 12.0, *) {
            activity.isEligibleForPrediction = true // 5
            activity.persistentIdentifier = NSUserActivityPersistentIdentifier("com.xdluoyang.Ruisi.sign") // 6
        } else {
            // Fallback on earlier versions
        }
        
        view.userActivity = activity // 7
        activity.becomeCurrent() // 8
        print("siri shortcut configed")
        
        return activity
    }

    
    @objc func dismissFormSiriShortCut() {
        dismiss(animated: true, completion: nil)
    }
    
    
    @IBAction func addSignToSiriClick(_ sender: UIButton) {
        let intent = setupIntents()
        if #available(iOS 12.0, *) {
            let shortcut = INShortcut(userActivity: intent)
            INVoiceShortcutCenter.shared.getAllVoiceShortcuts { (shortCuts, err) in
                for sh in shortCuts ?? [] {
                    if "com.xdluoyang.Ruisi.sign" == sh.shortcut.userActivity?.activityType {
                        // 编辑Siri短语
                        print("edit")
                        let editVoiceShortcutViewController = INUIEditVoiceShortcutViewController(voiceShortcut: sh)
                        editVoiceShortcutViewController.delegate = self
                        DispatchQueue.main.async {
                            self.present(editVoiceShortcutViewController, animated: true, completion: nil)
                        }
                        return
                    }
                }
                
                // 添加 Siri短语
                print("add")
                let viewController = INUIAddVoiceShortcutViewController(shortcut: shortcut)
                viewController.modalPresentationStyle = .formSheet
                viewController.delegate = self
                DispatchQueue.main.async {
                    self.present(viewController, animated: true, completion: nil)
                }
            }
        }
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        chooseAlert = UIAlertController(title: "选择心情", message: nil, preferredStyle: .actionSheet)
        chooseAlert.popoverPresentationController?.sourceView = btnSmiley
        chooseAlert.popoverPresentationController?.sourceRect = btnSmiley.bounds

        for v in items {
            let ac = UIAlertAction(title: v, style: .default, handler: handlePick)
            chooseAlert.addAction(ac)
        }

        chooseAlert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        //btnSmiley.titleLabel?.text = items[currentSelect]

        btnSmiley.setTitle(items[currentSelect], for: .normal)
        btnSmiley.setTitle(items[currentSelect], for: .focused)

        let date = Date()
        let calendar = Calendar.current
        let hour = calendar.component(.hour, from: date)

        if !(7 <= hour && hour < 24) {
            labelStatus.isHidden = false
            labelStatus.text = "不在签到时间 无法签到"

            haveSignImg.isHidden = true
            labelTotal.isHidden = true
            labelTotal2.isHidden = true

            labelSmiley.isHidden = true
            btnSmiley.isHidden = true
            inputText.isHidden = true
            btnSign.isHidden = true
        } else {
            checkSignStatus()
        }
    }
}

@available(iOS 12.0, *)
extension SignViewController: INUIAddVoiceShortcutViewControllerDelegate {
    func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController, didFinishWith voiceShortcut: INVoiceShortcut?, error: Error?) {
        print("did add:\(voiceShortcut?.invocationPhrase ?? "")")
        self.addToSiriBtn.setTitle("修改Siri捷径", for: .normal)
        controller.dismiss(animated: true, completion: nil)
    }
    
    func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) {
        print("canceled")
        controller.dismiss(animated: true, completion: nil)
    }
    
}

@available(iOS 12.0, *)
extension SignViewController: INUIEditVoiceShortcutViewControllerDelegate {
    func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didUpdate voiceShortcut: INVoiceShortcut?, error: Error?) {
        print("updated")
        controller.dismiss(animated: true, completion: nil)
    }
    
    func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didDeleteVoiceShortcutWithIdentifier deletedVoiceShortcutIdentifier: UUID) {
        print("deleted")
        controller.dismiss(animated: true, completion: nil)
    }
    
    func editVoiceShortcutViewControllerDidCancel(_ controller: INUIEditVoiceShortcutViewController) {
        print("cenceled")
        controller.dismiss(animated: true, completion: nil)
    }
}
